package com.meitianhui.convenitenbuy.module.home.ui.activity;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseToolbarActivity;
import com.meitianhui.convenitenbuy.config.InfoProvider;
import com.meitianhui.convenitenbuy.module.home.adapter.ZeroBuyAdapter;
import com.meitianhui.convenitenbuy.module.home.contract.ZeroBuyContract;
import com.meitianhui.convenitenbuy.module.home.di.DaggerHomeComponent;
import com.meitianhui.convenitenbuy.module.home.di.HomeModule;
import com.meitianhui.convenitenbuy.module.home.model.bean.HomeGoodsInfo;
import com.meitianhui.convenitenbuy.module.home.presenter.ZeroBuyPresenter;
import com.meitianhui.convenitenbuy.module.home.ui.activity.web.EdinburghWebViewActivity;
import com.meitianhui.convenitenbuy.widget.dialog.LoadingDialog;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

public class ZeroBuyActivity extends BaseToolbarActivity implements ZeroBuyContract.View {

    private int pageIndex = 1;
    private int pageSize = 16;

    private RecyclerView recyclerView;
    private View noDataView;
    private ImageView ivDataBg;
    private TextView tvDataContent;
    private LoadingDialog loadingDialog;
    private ZeroBuyAdapter adapter;
    private List<HomeGoodsInfo.Convient> list;

    private Gson gson = new Gson();
    @Inject
    ZeroBuyPresenter presenter;

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        DaggerHomeComponent.builder()
                .appComponent(App.getInstance().getAppComponent())
                .homeModule(new HomeModule(this))
                .build()
                .inject(this);
        setTbTitle("咚咚抢");
        isEnable(true);
        initIds();
        initData();
    }

    private void initIds() {
        recyclerView = getViewById(R.id.rv_zero_buy_grid);
        noDataView = getLayoutInflater().inflate(R.layout.data_empty_goods,
                (ViewGroup) recyclerView.getParent(), false);
        ivDataBg = (ImageView) noDataView.findViewById(R.id.iv_bg);
        tvDataContent = (TextView) noDataView.findViewById(R.id.tv_content);
    }

    private void initData() {
        if (list == null) list = new ArrayList<>();

        int numberOfColumns = 2;
        recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));
        // 10px
        recyclerView.addItemDecoration(new SpaceItemDecoration(10));

        adapter = new ZeroBuyAdapter(list);
        adapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                pageIndex ++;
                presenter.getZeroBuyGoodsList(String.valueOf(pageIndex), String.valueOf(pageSize));
            }
        }, recyclerView);

        // item click listener.
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                List dataSet = adapter.getData();
                HomeGoodsInfo.Convient currentData = (HomeGoodsInfo.Convient) dataSet.get(position);

                List<HomeGoodsInfo.Convient> list = new ArrayList<>();
                // 当 DataSet 中商品数大于3时，取当前 position 后面 2 个数据。
                if (dataSet.size() >= 3) {
                    for (int i = 0; i < 2; i++) {
                        position += 1;
                        if (position >= (dataSet.size() - 1)) position = 0;
                        list.add((HomeGoodsInfo.Convient) dataSet.get(position));
                    }
                }

                String json = gson.toJson(list);
                clickItem(currentData.getData_source(), currentData.getGoods_id(),
                        currentData.getPic_info_url(), json);
            }
        });
        recyclerView.setAdapter(adapter);

        // 主动调用 onRefreshData();
        onRefreshData();
    }

    private void clickItem(String dataSource, String goodId, String picInfoUrl, String json) {
        Intent intent = new Intent(this, EdinburghWebViewActivity.class);
        if (InfoProvider.getLoginStatus(this)) {
            intent.putExtra("url", Constants.HOST
                    + "h5/c/payback/zero/detail?goods_id=" + goodId
                    + "&mi=" + InfoProvider.getUserToken(App.getInstance()).getMember_id()
                    + "&mobile=" + InfoProvider.getUserToken(App.getInstance()).getMobile()
                    + "&list=" + json
                    + "&bind=1");
        } else {
            intent.putExtra("url", Constants.HOST
                    + "h5/c/payback/zero/detail?goods_id=" + goodId
                    + "&list=" + json
                    + "&bind=1");
        }
        intent.putExtra("title", "咚咚抢");
        intent.putExtra("is_second", true);
        intent.putExtra("goods_id", goodId);
        intent.putExtra("pic_url", picInfoUrl);
        startActivity(intent);
    }

    @Override
    protected int setView() {
        return R.layout.activity_zero_buy;
    }

    @Override
    protected void onRefreshData() {
        pageIndex = 1;
        presenter.getZeroBuyGoodsList(String.valueOf(pageIndex), String.valueOf(pageSize));
    }

    @Override
    public void getZeroBuyGoodsListSuccess(HomeGoodsInfo data) {
        refreshFinish();
        if (loadingDialog != null) {
            loadingDialog.stopProgressDialog();
        }

        List<HomeGoodsInfo.Convient> convients = null;
        if (data != null) {
            convients = data.getList();
        }
        final int size = convients == null ? 0 : convients.size();

        if (pageIndex == 1) {
            if (size == 0) {
                adapter.setEmptyView(noDataView);
            } else {
                list.clear();
                list.addAll(convients);
            }
        } else {
            if (size > 0) list.addAll(convients);
        }

        if (size < pageSize) {
            adapter.loadMoreEnd();
        } else {
            adapter.loadMoreComplete();
        }

        adapter.notifyDataSetChanged();
    }

    @Override
    public void showError(String msg) {
    }

    /**
     * RecyclerView 的设置间距。
     */
    public static class SpaceItemDecoration extends RecyclerView.ItemDecoration {

        private int space;

        public SpaceItemDecoration(int space) {
            this.space = space;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
                                   RecyclerView.State state) {
            outRect.left = space;
            outRect.bottom = space;

            // 每行只有 2 个，因此在第一个时设置左边距为0.
            if (parent.getChildLayoutPosition(view) % 2 == 0) {
                outRect.left = 0;
            }
        }
    }

}
